from functools import wraps
from flask import request, jsonify
from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity
from models import User, db

def login_required(f):
    """登录权限装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # 如果是OPTIONS请求，跳过认证检查
        if request.method == 'OPTIONS':
            return f(*args, **kwargs)
            
        try:
            verify_jwt_in_request()
            current_user_id = get_jwt_identity()
            # 将字符串ID转换为整数
            user = User.query.get(int(current_user_id))
            
            if not user:
                return jsonify({"error": "需要登录权限"}), 401
            return f(*args, **kwargs)
        except Exception as e:
            return jsonify({"error": "认证失败", "details": str(e)}), 401
    return decorated_function

def admin_required(f):
    """管理员权限装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # 如果是OPTIONS请求，跳过认证检查
        if request.method == 'OPTIONS':
            return f(*args, **kwargs)
            
        try:
            verify_jwt_in_request()
            current_user_id = get_jwt_identity()
            # 将字符串ID转换为整数
            user = User.query.get(int(current_user_id))
            
            if not user or user.role != 'admin':
                return jsonify({"error": "需要管理员权限"}), 403
            return f(*args, **kwargs)
        except Exception as e:
            return jsonify({"error": "认证失败", "details": str(e)}), 401
    return decorated_function

def teacher_required(f):
    """教师权限装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # 如果是OPTIONS请求，跳过认证检查
        if request.method == 'OPTIONS':
            return f(*args, **kwargs)
            
        try:
            verify_jwt_in_request()
            current_user_id = get_jwt_identity()
            # 将字符串ID转换为整数
            user = User.query.get(int(current_user_id))
            
            if not user or user.role not in ['teacher', 'admin']:
                return jsonify({"error": "需要教师权限"}), 403
            return f(*args, **kwargs)
        except Exception as e:
            return jsonify({"error": "认证失败", "details": str(e)}), 401
    return decorated_function

def student_required(f):
    """学生权限装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # 如果是OPTIONS请求，跳过认证检查
        if request.method == 'OPTIONS':
            return f(*args, **kwargs)
            
        try:
            verify_jwt_in_request()
            current_user_id = get_jwt_identity()
            # 将字符串ID转换为整数
            user = User.query.get(int(current_user_id))
            
            if not user or user.role not in ['student', 'teacher', 'admin']:
                return jsonify({"error": "需要登录权限"}), 403
            return f(*args, **kwargs)
        except Exception as e:
            return jsonify({"error": "认证失败", "details": str(e)}), 401
    return decorated_function

def get_current_user():
    """获取当前用户"""
    try:
        verify_jwt_in_request()
        current_user_id = get_jwt_identity()
        # 将字符串ID转换为整数
        return User.query.get(int(current_user_id))
    except Exception as e:
        return None
